package com.cxh.rmsq.ui.activity.self

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.BaseAdapter
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ColorUtils
import com.bumptech.glide.Glide
import com.cxh.rmsq.R
import com.cxh.rmsq.common.IntentExtra
import com.cxh.rmsq.db.model.MineBean
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.model.Resource2
import com.cxh.rmsq.model.Status
import com.cxh.rmsq.net.newNet.ProjectViewModel
import com.cxh.rmsq.ui.BaseActivity
import com.cxh.rmsq.ui.dialog.PhotoDialog
import com.cxh.rmsq.utils.CustomPermissionUtil
import com.cxh.rmsq.utils.GlideEngine
import com.cxh.rmsq.utils.MyGridView
import com.cxh.rmsq.utils.MyUtils
import com.cxh.rmsq.utils.RongGenerate
import com.cxh.rmsq.utils.TextSpanUtil
import com.cxh.rmsq.utils.ToastUtils
import com.cxh.rmsq.utils.dialog.IntroducePopup
import com.cxh.rmsq.utils.loadImage
import com.cxh.rmsq.utils.loading
import com.cxh.rmsq.viewmodel.UserInfoViewModel
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.contract.OnDatePickedListener
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.github.gzuliyujiang.wheelpicker.impl.UnitDateFormatter
import com.github.gzuliyujiang.wheelpicker.widget.DateWheelLayout
import com.hjq.shape.view.ShapeEditText
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnPermissionsInterceptListener
import com.luck.picture.lib.interfaces.OnRequestPermissionListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.permissions.PermissionChecker
import com.luck.picture.lib.permissions.PermissionConfig
import com.luck.picture.lib.permissions.PermissionResultCallback
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.util.XPopupUtils
import com.xuexiang.xui.utils.XToastUtils
import com.xuexiang.xui.widget.imageview.RadiusImageView
import java.util.Arrays
import java.util.Calendar


class EditUserInfoActivity : BaseActivity(), View.OnClickListener {

    private var photoDialog: PhotoDialog? = null
    var sex = -1
    var avatar = ""
    var birthday = ""
    var xingzuo = ""
    var province_id = ""
    var province_name = ""
    var city_id = ""
    var city_name = ""
    var arrayEducation =
        arrayOf<String>("博士", "硕士", "本科", "大专", "中专", "高中", "初中", "其他")

    var arrayCareer = arrayOf<String>(
        "农业",
        "林业",
        "畜牧业",
        "渔业",
        "采矿业",
        "制造业",
        "电力、热力、燃气及水生产和供应业",
        "建筑业",
        "批发和零售业",
        "交通运输、仓储和邮政业",
        "住宿和餐饮业",
        "信息传输、软件和信息技术服务业",
        "金融业",
        "房地产业",
        "租赁和商务服务业",
        "科学研究和技术服务业",
        "水利、环境和公共设施管理业",
        "居民服务、修理和其他服务业",
        "教育",
        "卫生和社会工作",
        " 文化、体育和娱乐业",
        "公共管理、社会保障和社会组织",
        "国际组织"
    )

    var arrayMbti = arrayOf<String>(
        "ESFP",
        "ESFJ",
        "ENFP",
        "ENFJ",
        "ESTP",
        "ESTJ",
        "ENTP",
        "ENTJ",
        "ISFP",
        "ISFJ",
        "INFP",
        "INFJ",
        "ISTP",
        "ISTJ",
        "INTP",
        "INTJ"
    )

    private val ivBack: LinearLayout by lazy { findViewById<LinearLayout>(R.id.iv_back) }
    private val ivPhoto: ImageView by lazy { findViewById<ImageView>(R.id.iv_photo) }
    private val ivHead: RadiusImageView by lazy { findViewById<RadiusImageView>(R.id.iv_head) }
    private val etName: EditText by lazy { findViewById<EditText>(R.id.et_name) }
    private val etIntro: TextView by lazy { findViewById<TextView>(R.id.et_intro) }
    private val tvBirthday: TextView by lazy { findViewById<TextView>(R.id.tv_birthday) }
    private val tvXingzuo: TextView by lazy { findViewById<TextView>(R.id.tv_xingzuo) }
    private val tvAddress: TextView by lazy { findViewById<TextView>(R.id.tv_address) }
    private val tvEducation: TextView by lazy { findViewById<TextView>(R.id.tv_education) }
    private val tvCareer: TextView by lazy { findViewById<TextView>(R.id.tv_career) }
    private val tvMbti: TextView by lazy { findViewById<TextView>(R.id.tv_mbti) }
    private val recyclerView: MyGridView by lazy { findViewById<MyGridView>(R.id.recyclerView) }
    private val tvSubmit: TextView by lazy { findViewById<TextView>(R.id.tv_submit) }
    private val radioGroup: RadioGroup by lazy { findViewById<RadioGroup>(R.id.radio_group) }
    private val rbBoy: RadioButton by lazy { findViewById<RadioButton>(R.id.rb_boy) }
    private val rbGirl: RadioButton by lazy { findViewById<RadioButton>(R.id.rb_girl) }
    private val stv_alipay: ShapeEditText by lazy { findViewById<ShapeEditText>(R.id.stv_alipay) }
    private val stv_wechat: ShapeEditText by lazy { findViewById<ShapeEditText>(R.id.stv_wechat) }
    private val tv_num_listener: TextView by lazy { findViewById<TextView>(R.id.tv_num_listener) }
    private var temp: CharSequence? = null

    private var mAdapter = PicAdapter()
    private var mData = mutableListOf<String>() //图片
    private var mDataPath = mutableListOf<String>() //选中后返回的
    var moreImgPath = ""
    var morePathList = mutableListOf<String>()
    var uploadImg = 1//1==头像  2==照片墙
    private var userInfoViewModel: UserInfoViewModel? = null
    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(ProjectViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_user_info)
        findViewById<LinearLayout>(R.id.cl_toolbar).setPadding(
            0,
            BarUtils.getStatusBarHeight(),
            0,
            0
        )
//        findViewById<ConstraintLayout>(R.id.cl_toolbar).setPadding(0, BarUtils.getStatusBarHeight(), 0, 0)
        BarUtils.setStatusBarColor(this, ColorUtils.getColor(R.color.transparent))
        BarUtils.setStatusBarLightMode(this, true)

        userInfoViewModel =
            ViewModelProviders.of(this).get<UserInfoViewModel>(UserInfoViewModel::class.java)
        ivBack.setOnClickListener(this)
        ivHead.setOnClickListener(this)
        tvBirthday.setOnClickListener(this)
        tvAddress.setOnClickListener(this)
        tvEducation.setOnClickListener(this)
        tvCareer.setOnClickListener(this)
        tvMbti.setOnClickListener(this)
        tvSubmit.setOnClickListener(this)
        etIntro.setOnClickListener(this)
        radioGroup.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_boy -> {
                    sex = 1
                }

                R.id.rb_girl -> {
                    sex = 2
                }
            }
        }

        recyclerView.adapter = mAdapter
        recyclerView.setOnItemClickListener { parent, view, position, id ->
            Log.i("posi", "${position} ** ${parent.childCount - 1}")
            if (position == parent.childCount - 1) {
                //addMainPicture()
//                SelectUpdatePic()
                transferPhoto()
            }
        }

        initData()
    }

    override fun onResume() {
        super.onResume()
        initAvatar()
    }
    private fun initData() {
        userInfoViewModel!!.upload()
            .observe(this@EditUserInfoActivity) { resource: Resource2<String?> ->
                if (resource.status == Status.SUCCESS && resource.data != null) {
                    loading(false)
                    if (uploadImg == 1) {
                        avatar = resource.data!!
                        Log.e("avatar", avatar)
                    } else {
//                    if (moreImgPath == "") {
//                        moreImgPath = it.data.toString()
//                    } else {
//                        moreImgPath = moreImgPath + "," + it.data
//                    }
//                    var listImg = ImgBean()

//                    listImg.ossId = it.data.toString()
                        morePathList.add(resource.data.toString())

                        Log.e("imgpath", moreImgPath)
                        Log.e("imgpath", morePathList.size.toString())
                    }
                }
            }
        userInfoViewModel!!.userSelfInfo.observe(this@EditUserInfoActivity) { resource: Resource2<MineBean?> ->
            if (resource.status == Status.SUCCESS && resource.data != null) {
                dismissLoadingDialog()
                val info = resource.data
                etName.setText(info.nickname)
                etName.setSelection(etName.text.toString().length)
                etName.isCursorVisible = true
                etName.requestFocus()

                etName.addTextChangedListener(object : TextWatcher {
                    override fun afterTextChanged(s: Editable?) {
                        tv_num_listener.text = "${temp!!.length}/7"
                        TextSpanUtil.setSpan(
                            tv_num_listener,
                            tv_num_listener.text.toString(),
                            arrayOf("/7"),
                            R.color.color_999999
                        )
                        if (temp!!.length > 7) {
                            XToastUtils.toast("输入不能超过50个字符！")
                        }

                    }

                    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

                    }

                    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                        temp = s
                    }

                })
                tv_num_listener.text = "${etName.text!!.length}/7"
                TextSpanUtil.setSpan(
                    tv_num_listener,
                    tv_num_listener.text.toString(),
                    arrayOf("/7"),
                    R.color.color_999999
                )
                if (!TextUtils.isEmpty(info.remark)) {
                    etIntro.setText(info.remark)
                }
                if (!TextUtils.isEmpty(info.zfbPayNum)) {
                    stv_alipay.setText(info.zfbPayNum)
                }
                if (!TextUtils.isEmpty(info.wxPayNum)) {
                    stv_wechat.setText(info.wxPayNum)
                }
                if (!TextUtils.isEmpty(info.birthday)) {
                    tvBirthday.text = info.birthday
//                tvXingzuo.text = info.constellation
                    tvXingzuo.text =
                        MyUtils.calculate(info.birthday!!.split("-")[1], info.birthday!!.split("-")[2])
                }
                xingzuo = tvXingzuo.text.toString().trim()
                tvEducation.text = info.highSchool
                if (!TextUtils.isEmpty(info.industry)) {
                    tvCareer.text = info.industry
                }
                if (!TextUtils.isEmpty(info.address)) {
                    tvAddress.text = info.address
                }
                tvMbti.text = info.mbti
                if (!TextUtils.isEmpty(info.avatar)) {
                    avatar = info.avatar!!
                    Glide.with(this)
                        .load(info.avatar)
                        .placeholder(R.drawable.rc_default_portrait)
                        .into(ivHead)
                } else {
                    avatar = RongGenerate.generateDefaultAvatar(
                        this, info.id.toString() + "", info.nickname
                    )
                    Glide.with(this)
                        .load(avatar)
                        .placeholder(R.drawable.rc_default_portrait)
                        .into(ivHead)
                }
                birthday = info.birthday.toString()
                sex = info.sex!!
                province_id = info.provinceCode.toString()
                province_name = info.provinceName.toString()
                city_id = info.cityCode.toString()
                city_name = info.cityName.toString()

                if (1 == info.sex) {
                    rbBoy.isChecked = true
                    rbGirl.isChecked = false
                } else {
                    rbBoy.isChecked = false
                    rbGirl.isChecked = true
                }

                if (info.photoList != null) {
                    for (j in 0 until info.photoList!!.size) {
                        mData.add(info.photoList[j]!!.toString())
//                        mData.add(it.data?.photoList[j]!!.url.toString())
                    }
//                    if (it.data?.photoList!!.size > 0) {
//                        moreImgPath = ""
//                        for (i in it.data?.photoList!!) {
//                            moreImgPath += "${i.ossId},"
//                        }
//                        moreImgPath = moreImgPath.substring(0, moreImgPath.length - 1)
////                    morePathList.addAll(mData)
//                    } else {
//                        moreImgPath = ""
//                        morePathList.clear()
//                    }
                    mAdapter.setData()

                    morePathList.addAll(info.photoList!!)
                }
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back -> {
                finish()
            }

            R.id.et_intro -> {
                popComment(1)
            }

            R.id.iv_head -> {
//                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//                    // 显示对话框告知用户权限使用目的
//                    val builder: AlertDialog.Builder = AlertDialog.Builder(this)
//                    builder.setTitle("权限申请")
//                        .setMessage("我们需要访问您的相机、存储权限，以便于图片上传、好友间发送照片以及实名认证等操作")
//                        .setPositiveButton("允许",
//                            DialogInterface.OnClickListener { dialog, which ->
//                                AppPermissionUtil.requestPermissions(this@EditUserInfoActivity,
//                                    arrayOf<String>(
//                                        Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
//                                    ),
//                                    object : AppPermissionUtil.OnPermissionListener {
//                                        override fun onPermissionGranted() {
//                                            photoDialog?.show()
//                                            uploadImg = 1
//                                        }
//
//                                        override fun onPermissionDenied() {
//
//                                        }
//
//                                    })
//                            })
//                        .setNegativeButton(
//                            "拒绝",
//                            DialogInterface.OnClickListener { dialog, which ->
//                                // 用户拒绝权限申请
//                            })
//                        .show()
//                } else {
                // 已获得权限，执行相关操作
                photoDialog?.show()
                uploadImg = 1
//                }

            }

            R.id.tv_birthday -> {
                popBirthday()
            }

            R.id.tv_address -> {
                selectAddress()
            }

            R.id.tv_education -> {
                popEducationBottom("请选择学历", arrayEducation, tvEducation)
            }

            R.id.tv_career -> {
                popEducationBottom("请选择行业", arrayCareer, tvCareer)
            }

            R.id.tv_mbti -> {
                popEducationBottom("请选择MBTI", arrayMbti, tvMbti)
            }

            R.id.tv_submit -> {
                if (TextUtils.isEmpty(avatar)) {
                    ToastUtils.showToast("请上传头像")
                    return
                }
                if (TextUtils.isEmpty(etName.text.toString().trim())) {
                    ToastUtils.showToast("请输入名字")
                    return
                }
                if (TextUtils.isEmpty(birthday)) {
                    ToastUtils.showToast("请选择出生日期")
                    return
                }
                if (TextUtils.isEmpty(tvAddress.text.toString().trim())) {
                    ToastUtils.showToast("请选择地区")
                    return
                }
//                if (TextUtils.isEmpty(tvEducation.text.toString().trim())) {
//                    ToastUtils.showToast("请选择学历")
//                    return
//                }
//                if (TextUtils.isEmpty(tvMbti.text.toString().trim())) {
//                    ToastUtils.showToast("请选择MBTI")
//                    return
//                }
                if (intent.getBooleanExtra("",false)){
                    if (TextUtils.isEmpty(stv_alipay.text.toString().trim())) {
                        ToastUtils.showToast("请填写支付宝账号")
                        return
                    }
                    if (TextUtils.isEmpty(stv_wechat.text.toString().trim())) {
                        ToastUtils.showToast("请填写微信账号")
                        return
                    }
                    if (!MyUtils.isWechatAccount(stv_alipay.text.toString().trim())){
                        stv_alipay.setText("")
                        ToastUtils.showToast("请输入正确的支付宝账号")
                        return
                    }
                    if (!MyUtils.isWechatAccount(stv_wechat.text.toString().trim())){
                        stv_wechat.setText("")
                        ToastUtils.showToast("请输入正确的微信账号")
                        return
                    }
                }

//                val mapOf = hashMapOf<String, Any>()
//                mapOf.put("avatar", avatar)
//                mapOf.put("nickname", etName.text.toString().trim())
//                mapOf.put("sex", sex)
//                mapOf.put("remark", etIntro.text.toString().trim())
//                mapOf.put("constellation", xingzuo)
//                mapOf.put("birthday", birthday)
//                mapOf.put("provinceName", province_name)
//                mapOf.put("provinceCode", province_id)
//                mapOf.put("cityName", city_name)
//                mapOf.put("cityCode", city_id)
//                mapOf.put("photoList", morePathList)
//                mapOf.put("address", tvAddress.text.toString().trim())
//                mapOf.put("highSchool", tvEducation.text.toString().trim())
//                mapOf.put("industry", tvCareer.text.toString().trim())
//                mapOf.put("mbti", tvMbti.text.toString().trim())
//                viewModel.getUserUpdate(mapOf)

                showLoadingDialog("")
                userInfoViewModel!!.updateUserinfo(
                    avatar,
                    etName.text.toString().trim(),
                    sex.toString(),
                    birthday,
                    etIntro.text.toString().trim(),
                    xingzuo,
                    province_name,
                    province_id,
                    city_name,
                    city_id,
                    morePathList,
                    tvAddress.text.toString().trim(),
                    tvEducation.text.toString().trim(),
                    tvCareer.text.toString().trim(),
                    tvMbti.text.toString().trim(),
                    stv_wechat.text.toString().trim(),
                    stv_alipay.text.toString().trim()
                )
                userInfoViewModel!!.updateUserinfo()
                    .observe(this) { resource: Resource2<String?> ->
                        if (resource.status == Status.SUCCESS && resource.data != null) {
                            IMManager.getInstance()
                                .updateUserInfoCache(
                                    IMManager.getInstance().currentId,
                                    etName.text.toString().trim(),
                                    Uri.parse(avatar),
                                    ""
                                )
                            val intent = Intent()
                            intent.putExtra("wechat", stv_wechat.text.toString().trim())
                            intent.putExtra("alipay", stv_alipay.text.toString().trim())
                            setResult(RESULT_OK, intent)
                            finish()
                        }
                    }
            }
        }
    }

    private fun popComment(type: Int) {
        XPopup.Builder(this@EditUserInfoActivity)
            .dismissOnTouchOutside(true)
            .dismissOnBackPressed(true)
            .asCustom(
                IntroducePopup(
                    this@EditUserInfoActivity,
                    etIntro.text.toString().trim(),
                    object : IntroducePopup.onClick {
                        override fun click(content: String, s1: String) {
                            etIntro.text = content
                        }
                    })
            ).show()
    }

    private fun initAvatar() {
        if (photoDialog == null) {
            photoDialog =
                PhotoDialog(this, true, 1, 1, R.style.BottomDialog)
        }

        photoDialog?.setOnClickListener(object : PhotoDialog.OnClickListener {
            override fun onPhotoPathResult(images: MutableList<String>) {
                loadImage(images[0], ivHead)
                loading(true)
                userInfoViewModel!!.uploadImg(images[0])
            }

            override fun onCameraPathResult(images: MutableList<String>) {
//                    mBinding.ivHead.setImageURI(images[0].toUri())
                loadImage(images[0], ivHead)
                loading(true)
                userInfoViewModel!!.uploadImg(images[0])
            }

        })
    }

    var pictureSelector: PictureSelector? = null

    @SuppressLint("SuspiciousIndentation")
    public fun transferPhoto() {
        uploadImg = 2
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//            // 显示对话框告知用户权限使用目的
//            val builder: AlertDialog.Builder = AlertDialog.Builder(this)
//            builder.setTitle("权限申请")
//                .setMessage("我们需要访问您的相机、存储权限，以便于图片上传、好友间发送照片以及实名认证等操作")
//                .setPositiveButton("允许",
//                    DialogInterface.OnClickListener { dialog, which ->
//                        AppPermissionUtil.requestPermissions(this@EditUserInfoActivity,
//                            arrayOf<String>(
//                                Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
//                            ),
//                            object : AppPermissionUtil.OnPermissionListener {
//                                override fun onPermissionGranted() {
//                                    picSelect()
//                                }
//
//                                override fun onPermissionDenied() {
//
//                                }
//
//                            })
//                    })
//                .setNegativeButton(
//                    "拒绝",
//                    DialogInterface.OnClickListener { dialog, which ->
//                        // 用户拒绝权限申请
//                    })
//                .show()
//        } else {
//            // 已获得权限，执行相关操作
        picSelect()
//        }

    }

    private fun picSelect() {
//        pictureSelector = PictureSelector.create(this)
        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage()) //全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
            .setSelectionMode(SelectModeConfig.MULTIPLE) // 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
            .isDisplayCamera(true) // 是否显示拍照按钮 true or false
            .setCameraImageFormat(PictureMimeType.PNG)

            .setImageEngine(GlideEngine.createGlideEngine())// 图片加载引擎 需要 implements ImageEngine接口
            .setMaxSelectNum(5 - morePathList.size) // 最大图片选择数量 int
            .setMinSelectNum(0) // 最小选择数量 int
            .setImageSpanCount(4) // 每行显示个数 int
//            .isZoomAnim(true) // 图片列表点击 缩放效果 默认true
//            .isEnableCrop(true)
//            .isCompress(true)
            .isGif(false)
            .isMaxSelectEnabledMask(true)
            .isOriginalControl(true)
            .isPageStrategy(true)
//            .circleDimmedLayer(false) // 是否圆形裁剪 true or false
//            .minimumCompressSize(100) // 小于100kb的图片不压缩
//            .synOrAsy(true) //同步true或异步false 压缩 默认同步
//            .isDragFrame(false) // 是否可拖动裁剪框(固定)
            .setPermissionsInterceptListener(object : OnPermissionsInterceptListener {
                override fun requestPermission(
                    fragment: Fragment,
                    permissionArray: Array<String>,
                    call: OnRequestPermissionListener
                ) {
                    val permissionInfoDialog = Dialog(fragment.requireActivity())
                    //应用上架要求添加权限使用说明
                    var permissionInfoTitle = ""
                    var permissionInfoContent = ""
                    if (Arrays.equals(
                            permissionArray,
                            PermissionConfig.getReadPermissionArray(
                                fragment.context,
                                SelectMimeType.ofImage()
                            )
                        )
                    ) {
                        permissionInfoTitle =
                            resources.getString(R.string.permission_info_title_storage)
                        permissionInfoContent =
                            resources.getString(R.string.permission_info_content_storage)
                    } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                        permissionInfoTitle =
                            resources.getString(R.string.permission_info_title_camera)
                        permissionInfoContent =
                            resources.getString(R.string.permission_info_content_camera)
                    }
                    if (!TextUtils.isEmpty(permissionInfoTitle) && !TextUtils.isEmpty(
                            permissionInfoContent
                        )
                    ) {
                        CustomPermissionUtil.showPermissionInfo(
                            fragment.activity,
                            permissionInfoDialog,
                            permissionInfoTitle,
                            permissionInfoContent
                        )
                    }

                    //此处使用图片选择框架的权限申请
                    PermissionChecker.getInstance().requestPermissions(
                        fragment,
                        permissionArray,
                        object : PermissionResultCallback {
                            override fun onGranted() {
                                permissionInfoDialog.dismiss()
                                call.onCall(permissionArray, true)
                            }

                            override fun onDenied() {
                                permissionInfoDialog.dismiss()
                                call.onCall(permissionArray, false)
                            }
                        })
                }

                override fun hasPermissions(
                    fragment: Fragment,
                    permissionArray: Array<String>
                ): Boolean {
                    return PermissionChecker.isCheckSelfPermission(
                        fragment.context,
                        permissionArray
                    )
                }
            })
            .setPermissionDeniedListener { fragment, permissionArray, requestCode, call -> //权限拒绝，弹出去设置弹窗，点击设置跳转到应用权限系统设置页面
                var permissionSetContent = ""
                if (Arrays.equals(
                        permissionArray,
                        PermissionConfig.getReadPermissionArray(
                            fragment.context,
                            SelectMimeType.ofImage()
                        )
                    )
                ) {
                    permissionSetContent = resources.getString(R.string.permission_set_storage)
                } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                    permissionSetContent = resources.getString(R.string.permission_set_camera)
                }
                if (!TextUtils.isEmpty(permissionSetContent)) {
                    CustomPermissionUtil.showPermissionSet(
                        fragment.activity,
                        permissionSetContent,
                        ArrayList(Arrays.asList(*permissionArray))
                    ) { call.onCall(true) }
                }
            }

            .forResult(object : OnResultCallbackListener<LocalMedia> {
                @SuppressLint("SuspiciousIndentation")
                override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                    if (result != null) {
                        val images: MutableList<String> = ArrayList()
                        for (localMedia in result) {
                            var path = localMedia.realPath.toString()

//                            localMedia.isCut()
//                            path = localMedia.cutPath
                            if (path.contains("content://")) {
                                val imgPath = getPath(path)
                                images.add(imgPath)
                            } else {
                                images.add(path)
                            }
                        }


                        var i = 0
                        mDataPath.clear()
                        while (i < images.size) {
                            var path = ""
                            path = images[i]
                            Log.i("path123", path)
                            mData.add(path)
                            mDataPath.add(path)
                            i++
                        }
                        mAdapter.setData()
                        for (j in 0 until mDataPath.size) {
                            viewModel.updateSinglePic(mDataPath.get(j)) {
                                runOnUiThread {
                                    morePathList.add(it.data.toString())
                                    Log.e("imgpath", morePathList.size.toString())
                                }
                            }
//                            userInfoViewModel!!.uploadImg(mDataPath[j])
//                            userInfoViewModel!!.upload()
//                                .observe(this@EditUserInfoActivity) { resource: Resource2<String?> ->
//                                    if (resource.status == Status.SUCCESS && resource.data != null) {
//
//    //                    if (moreImgPath == "") {
//    //                        moreImgPath = it.data.toString()
//    //                    } else {
//    //                        moreImgPath = moreImgPath + "," + it.data
//    //                    }
//    //                    var listImg = ImgBean()
//
//    //                    listImg.ossId = it.data.toString()
//                                        morePathList.add(resource.data.toString())
//
//                                        Log.e("imgpath", moreImgPath)
//                                        Log.e("imgpath", morePathList.size.toString())
//                                    }
//
//                                }
                        }
                    }
                }

                override fun onCancel() {
                }

            })
    }

    private fun getPath(path: String): String {
        if (!path.isEmpty()) {
            val uri = Uri.parse(path)
            val proj =
                arrayOf(MediaStore.Images.Media.DATA)
            val actualimagecursor: Cursor =
                contentResolver.query(uri, proj, null, null, null)!!
            val actual_image_column_index =
                actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            actualimagecursor.moveToFirst()
            val img_path = actualimagecursor.getString(actual_image_column_index)
            return img_path
        }
        return ""
    }

    private fun selectAddress() {
        val picker = AddressPicker(this)
        picker.setAddressMode(AddressMode.PROVINCE_CITY)
        picker.setOnAddressPickedListener { province, city, county ->

            province_id = province?.code.toString()
            city_id = city?.code.toString()
            province_name = province?.name.toString()
            city_name = city?.name.toString()
            tvAddress.setText("${province?.name} ${city?.name}")
            Log.e("address", province_id + "-------" + city_id)
        }
        picker.show()

    }

    private fun popBirthday() {
        val picker = DatePicker(this)
        picker.setTitle("请选择生日")
        val wheelLayout: DateWheelLayout = picker.getWheelLayout()
        wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
        //        wheelLayout.setDateLabel("年", "月", "日");
        wheelLayout.setDateFormatter(UnitDateFormatter())
        wheelLayout.setRange(DateEntity.target(1970, 1, 1), DateEntity.today(), DateEntity.today())
        //        wheelLayout.setCurtainEnabled(true);
        picker.getWheelLayout().setResetWhenLinkage(false)
        picker.setOnDatePickedListener(object : OnDatePickedListener {
            override fun onDatePicked(year: Int, month: Int, day: Int) {

                val birthDate: Calendar = Calendar.getInstance()
                birthDate.set(year, month, day)

                val thresholdDate: Calendar = Calendar.getInstance()
                thresholdDate.setTimeInMillis(birthDate.getTimeInMillis())
                thresholdDate.add(Calendar.YEAR, 18)

                val today: Calendar = Calendar.getInstance()

                // 3. 验证条件
                if (birthDate.after(today)) {
                    Toast.makeText(
                        this@EditUserInfoActivity,
                        "出生日期不能在未来",
                        Toast.LENGTH_SHORT
                    ).show()
                } else if (!thresholdDate.after(today)) {
                    val stringBuilder = StringBuilder()
                    stringBuilder.append(year).append("-")
                    if (month < 10) {
                        stringBuilder.append("0")
                    }
                    stringBuilder.append(month).append("-")
                    if (day < 10) {
                        stringBuilder.append("0")
                    }
                    stringBuilder.append(day)
                    tvBirthday.setText(stringBuilder)
                    birthday = tvBirthday.text.toString()

                    tvXingzuo.text =
                        MyUtils.calculate(birthday.split("-")[1], birthday.split("-")[2])
                    Log.e(
                        "dayyyyy",
                        birthday.split("-")[1].toString() + "---" + birthday.split("-")[2].toString()
                    )
                    xingzuo = tvXingzuo.text.toString().trim()
                } else {
                    tvBirthday.setText("")
                    birthday = ""
                    tvXingzuo.setText("")
                    xingzuo = ""
                    Toast.makeText(this@EditUserInfoActivity, "必须年满 18 岁", Toast.LENGTH_SHORT)
                        .show()
                }
            }
        })
        picker.show()
    }

    private fun popEducationBottom(title: String, data: Array<String>, view: TextView) {
        XPopup.Builder(this)
            .isDarkTheme(false)
            .hasShadowBg(true)
            .moveUpToKeyboard(false)
            .autoOpenSoftInput(false)
            .borderRadius(XPopupUtils.dp2px(this, 15f).toFloat())
            .maxHeight((XPopupUtils.getAppHeight(this) as Int * .65f).toInt())
            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
            .asBottomList(
                title, data
            )  // null, /** 图标Id数组，可无 **/
            // 1,    /** 选中的position，默认没有选中效果 **/
            // enableGesture, /** 是否启用手势交互，默认启用。手势交互模式下，无法设置其他的动画器；禁用后无法进行手势交互，但是可以设置动画器 **/
            { position, text ->
                view.setText(text)
            }
            .show()
    }


    inner class PicAdapter : BaseAdapter() {
        private var mUris: List<Uri>? = null
        private var mPaths: List<String>? = null
        fun setData(uris: List<Uri>?, paths: List<String>?) {
            mUris = uris
            mPaths = paths
            notifyDataSetChanged()
        }

        fun setData() {
            notifyDataSetChanged()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            val view: View?
            val viewHolder: ViewHolder

            if (convertView == null) {
                val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
                // 需要创建视图 animals_list
                view = inflater.inflate(R.layout.item_grid_picture, null)
                viewHolder = ViewHolder(view)
                view?.tag = viewHolder

            } else {
                view = convertView
                viewHolder = view.tag as ViewHolder
            }

            if (position < mData.size) {
                loadImage(mData[position], viewHolder.imgUrl!!)
                Log.i("uri", mData[position])
                viewHolder.deleteImg!!.visibility = View.VISIBLE
            } else {
                loadImage(R.mipmap.icon_add_img_publish_baseinfo, viewHolder.imgUrl!!)
                Log.i("size + ", "走了")
                viewHolder.deleteImg!!.visibility = View.GONE
            }
            viewHolder.deleteImg!!.setOnClickListener {
                mData.removeAt(position)
//                mDataPath.removeAt(position)
                notifyDataSetChanged()
                morePathList.clear()
                if (mData.size > 0) {
//                    moreImgPath = ""
//                    for (i in mData) {
//                        moreImgPath += "$i,"
//                    }
//                    moreImgPath = moreImgPath.substring(0, moreImgPath.length - 1)
                    morePathList.addAll(mData)
                } else {
                    moreImgPath = ""

                }

            }

            viewHolder.imgUrl!!.setOnClickListener {
                if (position == mData.size) {
                    //addMainPicture()
//                    SelectUpdatePic()
                    transferPhoto()
                } else {//这里可以添加查看大图的逻辑
                    /*Intent intent = new Intent(parent.getContext(), FriendCircleReleaseActivity.class);
                    intent.putExtra("position", position);
                    intent.putStringArrayListExtra("urlList", mData);
                    startActivity(intent);*/
                }
            }

            if (position < mData.size) {

            }
            return view as View
        }

        override fun getItem(position: Int): Any {
            return mData.get(position)
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getCount(): Int {
            return if (mData.size < 5) {
                if (mData == null) 0 else mData.size + 1
            } else {
                if (mData == null) 0 else mData.size
            }
        }

        private inner class ViewHolder(view: View?) {
            var imgUrl: RadiusImageView? = null
            var deleteImg: ImageView? = null

            init {
                this.imgUrl = view?.findViewById(R.id.img_url)
                this.deleteImg = view?.findViewById(R.id.delete_picture)
            }
        }
    }

}